xquery version "1.0";

(:~
	Authentication for the users in the application.
:)

declare namespace MedEx="http://localhost:8080/exist/MedEx";
declare namespace system="http://exist-db.org/xquery/system";
import module namespace util="http://exist-db.org/xquery/util";
import module namespace request="http://exist-db.org/xquery/request";
import module namespace session="http://exist-db.org/xquery/session";
import module namespace xdb="http://exist-db.org/xquery/xmldb";

declare option exist:serialize "method=xml media-type=text/xml omit-xml-declaration=no indent=no";

(:~
	Checks if the user is in the user list.
	Checks if the password is correct
	Returns the result of the authentication
:)
declare function MedEx:do-login($user as xs:string*, $pass as xs:string*) as element()*
{
		let $users := collection("/db/pgh")//user
		let $message := (
			for $person in $users
			let $username := $person/username/text()
			let $password := $person/password/text()
			let $access := $person/account/text()
			return
				if($username eq $user) then
					(if($password eq $pass) then
						$person
					 else <error>Wrong Password</error>
					)
				else <error>Invalid Username</error>
			)
		return
		if($message/account/text()) then
			<success><user>{$message/username/text()}</user><account>{$message/account/text()}</account></success>
		else if ($message/text() = "Wrong Password") then
			<error>Wrong Password</error>
		else
			<error>Invalid Username</error>
		
			
};
session:create(),
let $user := request:get-parameter("user", ())
let $pass := request:get-parameter("pass", ())
return 
	MedEx:do-login($user, $pass)
